<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>搜索条件</span>
          <el-button link type="primary" @click="toggleFilterExpand">
            {{ filterExpanded ? '收起' : '展开' }}
            <el-icon>
              <ArrowDown v-if="!filterExpanded" />
              <ArrowUp v-else />
            </el-icon>
          </el-button>
        </div>
      </template>

      <div class="filter-container" :class="{ 'filter-collapsed': !filterExpanded }">
        <el-form :inline="true" :model="queryParams" @keyup.enter="handleQuery">
          <el-form-item label="配置代码">
            <el-input v-model="queryParams.code" placeholder="请输入配置代码" clearable @clear="handleQuery">
              <template #prefix>
                <el-icon><Document /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item class="search-buttons-container">
            <div class="search-buttons">
              <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
              <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>系统参数列表</span>
        </div>
      </template>

      <div class="table-container">
        <div class="table-toolbar">
          <div class="left-buttons">
            <el-button type="primary" :icon="Plus" @click="handleAdd">新增配置</el-button>
          </div>
        </div>

        <el-table 
          v-loading="loading" 
          :data="configList" 
          size="default"
          border 
          stripe
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="index" label="#" width="60" />
          <el-table-column prop="code" label="配置代码" min-width="120" show-overflow-tooltip />
          <el-table-column prop="value" label="配置值" min-width="200" show-overflow-tooltip />
          <el-table-column prop="remarks" label="备注" min-width="150" show-overflow-tooltip />
          <el-table-column prop="create_time" label="创建时间" min-width="160" show-overflow-tooltip>
            <template #default="scope">
              {{ formatDateTime(scope.row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="update_time" label="更新时间" min-width="160" show-overflow-tooltip>
            <template #default="scope">
              {{ formatDateTime(scope.row.update_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="scope">
              <div class="table-operation-buttons">
                <el-button type="warning" link :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
                <el-popconfirm
                  :title="`确认删除配置 ${scope.row.code} 吗?`"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  @confirm="handleDelete(scope.row)"
                >
                  <template #reference>
                    <el-button type="danger" link :icon="Delete">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-if="total > 0"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="550px" 
      destroy-on-close
      center
      align-center
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form ref="configFormRef" :model="configForm" :rules="configRules" label-width="100px" status-icon>
        <el-form-item label="配置代码" prop="code">
          <el-input v-model="configForm.code" placeholder="请输入配置代码" :disabled="!!configForm.id">
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="配置值" prop="value">
          <el-input v-model="configForm.value" type="textarea" :rows="4" placeholder="请输入配置值" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="configForm.remarks" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Plus, Edit, Delete, Search, Refresh, 
  Document, ArrowDown, ArrowUp 
} from '@element-plus/icons-vue'
import { getSysConfigs, getSysConfig, createSysConfig, updateSysConfig, deleteSysConfig } from '@/api/sys-config'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  code: ''
})

// 表单对象
const configForm = reactive({
  id: undefined,
  code: '',
  value: '',
  remarks: '',
  version: 1
})

// 表单校验规则
const configRules = {
  code: [{ required: true, message: '配置代码不能为空', trigger: 'blur' }],
  value: [{ required: true, message: '配置值不能为空', trigger: 'blur' }]
}

// 数据列表
const configList = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const configFormRef = ref()
const submitLoading = ref(false)

// UI控制变量
const filterExpanded = ref(true)

// 切换筛选器展开/收起
const toggleFilterExpand = () => {
  filterExpanded.value = !filterExpanded.value
}

// 获取配置列表
const getConfigList = async () => {
  loading.value = true
  try {
    const params = {
      skip: (queryParams.pageNum - 1) * queryParams.pageSize,
      limit: queryParams.pageSize,
      code: queryParams.code.trim() || undefined
    }
    
    const res = await getSysConfigs(params)
    configList.value = res.data || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getConfigList()
}

// 重置查询
const resetQuery = () => {
  queryParams.code = ''
  queryParams.pageNum = 1
  getConfigList()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getConfigList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getConfigList()
}

// 添加配置
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '添加系统参数'
  dialogVisible.value = true
}

// 对话框关闭处理
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 编辑配置
const handleEdit = async (row) => {
  resetForm()
  dialogTitle.value = '编辑系统参数'
  
  try {
    const res = await getSysConfig(row.id)
    Object.assign(configForm, res.data || res)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取配置详情失败:', error)
    ElMessage.error('获取配置详情失败')
  }
}

// 删除配置
const handleDelete = async (row) => {
  try {
    await deleteSysConfig(row.id)
    ElMessage.success('删除成功')
    getConfigList()
  } catch (error) {
    console.error('删除配置失败:', error)
    ElMessage.error('删除配置失败')
  }
}

// 重置表单
const resetForm = () => {
  // 重置表单数据
  Object.assign(configForm, {
    id: undefined,
    code: '',
    value: '',
    remarks: '',
    version: 1
  })
  
  // 使用 nextTick 确保 DOM 更新后再重置表单验证
  nextTick(() => {
    if (configFormRef.value) {
      configFormRef.value.resetFields()
      configFormRef.value.clearValidate()
    }
  })
}

// 提交表单
const submitForm = () => {
  configFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (configForm.id) {
          // 编辑
          await updateSysConfig(configForm.id, configForm)
          ElMessage.success('修改成功')
        } else {
          // 新增
          await createSysConfig(configForm)
          ElMessage.success('添加成功')
        }
        handleDialogClose() // 使用统一的对话框关闭处理
        getConfigList()
      } catch (error) {
        console.error('保存配置失败:', error)
        ElMessage.error('保存配置失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  getConfigList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out;
  max-height: 300px;
  overflow: hidden;
  opacity: 1;
  
  &.filter-collapsed {
    max-height: 0;
    opacity: 0;
  }
}

.table-operation-buttons {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
  gap: 5px;
  
  .el-button {
    margin: 0;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  
  .el-button {
    margin-left: 8px;
  }
}
</style>
